package org.okkam.refine.model;
 
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class FileLogger{
 
    private File logFile;
 
    private long logEntryNo = 0;
 
    private static FileLogger instance = null;
 
    public static final String DEFAULT_LOG_FILEPATH = "bin/Log/Daemon.log";
 
    public FileLogger(String logFilePath){
        logFile = new File(logFilePath);
        try{
            logFile.createNewFile();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        
        instance = this;
    }
 
    public FileLogger(File logFile){
        this.logFile = logFile;
       
        instance = this;
    }
 
    public static FileLogger getInstance(){
        return instance;
    }
 
    /**
     * Adds and entry in the log file but also echos the log to standard out
     *
     * @param data
     * @param printToStdOut
     */
 
    public void add(String data,boolean printToStdOut){
        if (printToStdOut){
            System.out.print("\n" + data + "\n");
        }
        add(data);
    }
 
    /**
     * Add a log file entry
     *
     * @param data
     */
 
    public synchronized void add(String data){
        DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
        Date date = new Date();
        String dateTime = dateFormat.format(date);
 
        try{
            if (logFile.createNewFile()){
                FileWriter fileWriter = new FileWriter(logFile);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(data);
                bufferedWriter.newLine();
                bufferedWriter.close();
            }
            else{
                FileWriter fileWriter = new FileWriter(logFile,true);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(data);
                bufferedWriter.newLine();
                bufferedWriter.close();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String...argv){
        FileLogger myFileLogger = new FileLogger("/home/seidm/okkam/log/test.log");
        myFileLogger.add("my next to last log entry");
        myFileLogger.add("my last log entry");
    }
 
}